let { Users, AccountInfo, BankCard, CardExchange, CardTransfer } = require('../models');
let auth = require('../utils/auth');
let ids = 1;

let index_fn = async (ctx, next) => {
    let uid = ctx.session.userId;
    let username = ctx.session.userName;

    let obj = {
        username: username,
        uid: uid
    };
    ctx.render('index.html', obj);
}
let login_fn = async (ctx, next) => {
    ctx.render('login.html');
}
let register_fn = async (ctx, next) => {
    ctx.render('register.html')
}

let loginDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';

    console.log(username);
    console.log(password);
    let res;
    let u1 = await Users.findOne({
        where: {
            username: username,
            password: password
        }
    }).then((row) => {
        let user = JSON.stringify(row);
        let u2 = JSON.parse(user);
        console.log(user);
        console.log(u2);

        if (user !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = { code: 200, msg: '登录成功' };
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请重试' };
        }
    });
    ctx.body = res;
}
let registerDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';
    let confirmpassword = ctx.request.body.confirmpassword || '';

    console.log(username);
    console.log(password);
    console.log(confirmpassword);

    if (username.length > 0 && password.length > 0 && confirmpassword.length > 0 && password === confirmpassword) {
        let userDemo = await Users.findOne({ where: { username: username } });
        console.log(JSON.stringify(userDemo));
        let res = '';

        // 如果有找到同名的用户，则返回提示消息，并且不创建用户；否则创建用户，并返回提示消息
        if (userDemo) {
            // msg='当前用户名已经注册，请确认后重试';
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        } else {
            let u1 = Users.create({
                username: username,
                password: password
            });
            res = { code: 200, msg: '注册成功' };
        }

        ctx.body = JSON.stringify(res);
        // ctx.render('login.html');
    } else {
        console.log('用户名或密码不能为空；并且两次密码应该相同');
    }
}
let logout_fn = async (ctx, next) => {
    ctx.session = null;

    ctx.body = { code: 200, msg: '注销成功' };
}

let forgot_fn = async (ctx, next) => {
    ctx.render('forgot.html')
}

let add_fn = async (ctx, next) => {
    let uId = ctx.session.userId;
    let AccountPhone = ctx.request.body.phoneNumber;
    let RealName = ctx.request.body.realName;
    let money = ctx.request.body.advanceDeposit;
    let pwd = ctx.request.body.transactionPwd;
    let OpenTime = new Date().toLocaleDateString().replace(/\//g, '-');
    var jschars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    var Code = "";
    for (var i = 0; i < 18; i++) {
        var id = Math.ceil(Math.random() * 9);
        Code += jschars[id];
    }
    let justOne = await BankCard.count({
        where: {
            UserId: uId
        }
    })
    if (justOne == 0 && AccountPhone.length != 0 && RealName.length != 0 && money.length != 0 && pwd.length != 0) {
        let addA = await AccountInfo.create({
            UserId: uId,
            AccountCode: Code,
            AccountPhone: AccountPhone,
            RealName: RealName,
            OpenTime: OpenTime,
            remarks: "开户"
        })
        let addC = await BankCard.create({
            CardNo: Code,
            CardBalance: money,
            UserId: uId,
            CardPwd: pwd,
            CardState: 1,
            CardTime: OpenTime,
            remarks: "开卡"
        })
        let data = JSON.stringify(addA, addC);

        ctx.body = { code: 200, data, msg: '开户成功,请在查询处查看卡号' }
    } else if (justOne == 1) {
        let data = JSON.stringify(justOne);
        ctx.body = { code: 500, data, msg: '一个账号只能开一个户' }
    } else {
        ctx.body = { code: 404, msg: '请不要留空' }
    }
}

let find_fn = async (ctx, next) => {
    let uid = ctx.session.userId;
    let justOne = await BankCard.count({
        where: {
            UserId: uid
        }
    })
    if (justOne == 0) {
        ctx.body = { code: 404, msg: '您还没有开户 请先去开户' }
    } else {
        let selectCard = await BankCard.findAll({
            where: {
                UserId: uid
            }
        })
        ctx.body = { code: 200, selectCard, msg: '查询成功' }
    }

}

let save_fn = async (ctx, next) => {
    let uid = ctx.session.userId;
    let cardNo = ctx.request.body.cardNo;
    let cardBalanceNew = ctx.request.body.moneyNew;
    let justOne = await BankCard.count({
        where: {
            UserId: uid
        }
    })
    if (justOne == 0) {
        ctx.body = { code: 404, msg: '您还没有开户 请先去开户' }
    } else {
        let selectCard = await BankCard.findAll({
            where: {
                UserId: uid
            }
        })
        let cardBalanceOld = selectCard[0].CardBalance;

        let HaveCard = await BankCard.count({
            where: {
                CardNo: cardNo,
                UserId: uid
            }
        })
        if (HaveCard == 0) {
            ctx.body = { code: 404, msg: '卡号不存在,请检查' }
        } else {
            let updateCard = await BankCard.update({
                CardBalance: Number(cardBalanceOld) + Number(cardBalanceNew)
            },
                {
                    where: {
                        CardNo: cardNo
                    }
                })
            ctx.body = { code: 200, updateCard, msg: '存款成功' }
        }

    }
}

let outMoney_fn = async (ctx,next) => {
    let uid = ctx.session.userId;
    let cardNo = ctx.request.body.cardNo;
    let cardBalanceNew = ctx.request.body.moneyout;

    let justOne = await BankCard.count({
        where: {
            UserId: uid
        }
    })
    if (justOne == 0) {
        ctx.body = { code: 404, msg: '您还没有开户 请先去开户' }
    } else {
        let selectCard = await BankCard.findAll({
            where: {
                UserId: uid
            }
        })
        let cardBalanceOld = selectCard[0].CardBalance;

        let HaveCard = await BankCard.count({
            where: {
                CardNo: cardNo,
                UserId: uid
            }
        })
        if (HaveCard == 0) {
            ctx.body = { code: 404, msg: '卡号不存在,请检查' }
        } else {
            let updateCard = await BankCard.update({
                CardBalance: Number(cardBalanceOld) - Number(cardBalanceNew)
            },
                {
                    where: {
                        CardNo: cardNo
                    }
                })
            ctx.body = { code: 200, updateCard, msg: '取款成功' }
        }

    }

}

let transfer_fn = async (ctx,next) => {
    let uid = ctx.session.userId;
    let cardNo = ctx.request.body.cardNo;
    let cardBalanceNew = ctx.request.body.transfer;

    let justOne = await BankCard.count({
        where: {
            UserId: uid
        }
    })
    if (justOne == 0) {
        ctx.body = { code: 404, msg: '您还没有开户 请先去开户' }
    } else {
        let selectCard = await BankCard.findAll({
            where: {
                UserId: uid
            }
        })
        let cardBalanceOld = selectCard[0].CardBalance;

        let HaveCard = await BankCard.count({
            where: {
                CardNo: cardNo,
                UserId: uid
            }
        })
        if (HaveCard == 0) {
            ctx.body = { code: 404, msg: '卡号不存在,请检查' }
        } else {
            let updateCard = await BankCard.update({
                CardBalance: Number(cardBalanceOld) - Number(cardBalanceNew)
            },
                {
                    where: {
                        CardNo: cardNo
                    }
                })
            ctx.body = { code: 200, updateCard, msg: '转账成功' }
        }

    }

}

let change_fn = async (ctx, next) => {
    let uid = ctx.session.userId;
    let cardNo = ctx.request.body.cardNo;
    let pwdNew = ctx.request.body.pwdNew;
    let justOne = await BankCard.count({
        where: {
            UserId: uid
        }
    })
    if (justOne == 0) {
        ctx.body = { code: 404, msg: '您还没有开户 请先去开户' }
    } else {
        let HaveCard = await BankCard.count({
            where: {
                CardNo: cardNo,
                UserId: uid
            }
        })
        if (HaveCard == 0) {
            ctx.body = { code: 404, msg: '卡号不存在,请检查' }
        } else {
            let updateCardPwd = await BankCard.update({
                CardPwd: pwdNew
            },
                {
                    where: {
                        CardNo: cardNo
                    }
                })
            ctx.body = { code: 200, updateCardPwd, msg: '改密成功' }
        }

    }
}

//注销确定路由
let deleteCarDone_fn = async (ctx, next) => {

    
    console.log(ids);
    // let deleteCar= await
    AccountInfo.destroy({ where: { UserId: ids } });

    let res = { code: 200, msg: '删除成功' };

    ctx.body = JSON.stringify(res);
   
}
let lost_fn = async (ctx, next) => {
    console.log(111);
   
}

module.exports = {
    '/': ['get', auth, index_fn],
    '/login': ['get', auth, login_fn],
    '/logout': ['post', logout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/forgot': ['get', forgot_fn],
    '/add': ['post', add_fn],
    '/find': ['get', find_fn],
    '/save': ['post', save_fn],
    '/change': ['post', change_fn],
    '/outMoney':['post',outMoney_fn],
    '/transfer':['post',transfer_fn],
    '/deleteCarDone': ['post', deleteCarDone_fn],
    '/lost': ['post', lost_fn],  
}